<template>
  <el-card style="height: 100%">
    <!-- 1.面包屑 -->
    <MyBread url="coach" level1="学员预约情况" />
    <!-- 按钮--筛选 -->
    <el-button
      type="primary"
      @click="showAllRecord()"
      style="margin-top: 20px"
    >显示所有预约记录</el-button>
    <el-button
      type="primary"
      @click="showTodayRecord()"
      style="margin-top: 20px"
    >显示今天预约记录</el-button>
    <el-button
      type="primary"
      @click="showTomorrowRecord()"
      style="margin-top: 20px"
    >显示明天预约记录</el-button>
    <!-- 2.表格 -->
    <el-table
      :data="FilterStudentAppointList"
      style="width: 100%; margin-top: 15px"
      max-height="700px"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column
        prop="identify"
        label="身份证号"
        width="230"
      ></el-table-column>
      <el-table-column
        prop="studentName"
        label="姓名"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="selectedDate"
        label="预约日期"
        width="130"
      ></el-table-column>
      <el-table-column
        prop="selectTimeInterval"
        label="预约时间段"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="submitTime"
        label="提交预约时间"
        width="240"
      ></el-table-column>
      <el-table-column
        prop="confirmTime"
        label="确认预约时间"
        width="240"
      ></el-table-column>
      <el-table-column label="是否确认预约" width="170">
        <template slot-scope="scoped">
          <el-switch
            v-model="scoped.row.isSure"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否"
            disabled
            class="switch"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scoped">
          <el-button
            type="primary"
            size="mini"
            round
            @click="confirmAppoint(scoped.row)"
          >确认预约</el-button>
          <el-button
            type="danger"
            size="mini"
            round
            @click="deleteAppoint(scoped.row)"
          >删除预约</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "StudentAppoint",
  data() {
    return {
      StudentAppointList: [], // 学员预约数据
      FilterStudentAppointList: [], // 过滤学员预约数据
      Counter: {}, // 预约计数
      CoachTimeArrange: {}, // 教练练车时间安排
    };
  },
  methods: {
    // 确认预约
    async confirmAppoint(row) {
      if (!(await this.haveThisPermission(this.$route.path, "确认预约"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 判断是否已经确认预约，若已确认弹出及警告
      if (!row.isSure) {
        this.$confirm("是否确认预约", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info",
        })
          .then(async (res) => {
            // 判断预约的时间是否过去 -- 今天之前的日期
            if (new Date(row.selectedDate).getTime() <= new Date().getTime()) {
              this.$message.warning("该时间预约已经过去，不可确认");
              return false;
            }
            // 判断各时间段人数是否达到上限
            if (
              this.Counter[row.selectedDate][row.selectTimeInterval] >=
              this.CoachTimeArrange.TrainNumber
            ) {
              this.$message.warning("该时间段预约人数已达到上线");
              return false;
            }
            // 确认并修改数据库数据
            row.isSure = true;
            row.confirmTime = new Date().toLocaleString();
            await this.$https.updateUserData("/studentAppoint", row.id, row);
            this.Counter[row.selectedDate][row.selectTimeInterval]++;
            this.$message.success("已确认预约");
          })
          .catch(() => {
            this.$message.info("已取消确认");
          });
      } else {
        this.$message.warning("已确认预约，不可再次确认");
      }
    },
    // 删除预约
    async deleteAppoint(row) {
      if (!(await this.haveThisPermission(this.$route.path, "删除预约"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      this.$confirm("是否删除该预约", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      })
        .then(async () => {
          await this.$https.deleteUserData("/studentAppoint", row.id);
          // 判断删除的数据是否已经确认预约，若已确认预约，该时间段人数减1
          if (row.isSure) {
            this.Counter[row.selectedDate][row.selectTimeInterval]--;
          }
          this.$message.success("已删除该预约");
          // 重新获取数据
          const { data } = await this.$https.getUserData({
            url: "/studentAppoint",
            id: this.CurrentCoachInfo.id,
          });
          this.FilterStudentAppointList = this.StudentAppointList = data;
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 完成计数功能
    handleCounting(array) {
      // 获取不同日期
      const DateCountSet = new Set();
      array.forEach((element) => {
        // 只保存今天及之后日期
        DateCountSet.add(element.selectedDate);
      });
      // 根据不同日期创建对象
      const IntervalCountSet = new Set();
      DateCountSet.forEach((element) => {
        this.Counter[element] = {};
        array.forEach((ele) => {
          if (ele.selectedDate === element) {
            IntervalCountSet.add(ele.selectTimeInterval);
            this.Counter[element][ele.selectTimeInterval] = 0;
          }
        });
      });
      // 完成不同日期不同时间段【确认预约人数】功能
      array.forEach((element) => {
        if (element.isSure) {
          this.Counter[element.selectedDate][element.selectTimeInterval]++;
        }
      });
    },
    // 显示今天预约记录
    showTodayRecord() {
      const date = new Date();
      this.FilterStudentAppointList = this.StudentAppointList.filter(
        (element) => {
          const mydate = new Date(element.selectedDate);
          return (
            date.getTime() - 3600 * 1000 * 24 < mydate.getTime() &&
            mydate.getTime() < date.getTime()
          );
        }
      );
    },
    // 显示明天预约记录
    showTomorrowRecord() {
      const date = new Date();
      this.FilterStudentAppointList = this.StudentAppointList.filter(
        (element) => {
          const mydate = new Date(element.selectedDate);
          return (
            date.getTime() < mydate.getTime() &&
            mydate.getTime() < date.getTime() + 3600 * 1000 * 24
          );
        }
      );
    },
    // 显示所有记录
    showAllRecord() {
      this.FilterStudentAppointList = this.StudentAppointList;
    },
  },
  computed: {
    ...mapState("CoachModule", ["CurrentCoachInfo"]),
  },
  async mounted() {
    // 获取登录教练的信息
    await this.$store.dispatch("CoachModule/getCurrentCoachInfo");
    // 根据教练 id 获取学员预约数据
    const { data } = await this.$https.getUserData({
      url: "/studentAppoint",
      id: this.CurrentCoachInfo.id, // 这里的id相当于学员的coachID
    });
    this.FilterStudentAppointList = this.StudentAppointList = data;
    this.handleCounting(
      this.StudentAppointList.filter((element) => {
        return (
          new Date(element.selectedDate).getTime() >=
          new Date().getTime() - 3600 * 1000 * 24
        );
      })
    );
    // 获取教练预约安排情况
    const { data: arrange } = await this.$https.getUserData({
      url: "/timeArrange",
      identify: this.CurrentCoachInfo.identify,
    });
    this.CoachTimeArrange = arrange[0];
  },
};
</script>